<script lang="ts" setup>
import {ref} from 'vue';

const rechargeRecords =ref([{
  "recordid": '',
  "rechargetime": '',
  "balanceafter": '',
  "paymentmethod": '',
  "userid": '',
  "realname":''
},]);

//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(10)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  rechargeRecordsList();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num
  rechargeRecordsList();
}

import useUserInfoStore from "@/stores/userInfo.js";
const userInfoStore = useUserInfoStore();
const isAdmin=(userInfoStore.userInfo.usertype===1);
//用来搜索用户名
const name= ref('')

import {rechargeInfoService,rechargeNewRecordService,R_rechargeInfoService} from "@/api/recharge.js"
import {ElMessage} from "element-plus";
const rechargeRecordsList=async ()=> {
  let result
  if (isAdmin) {
    let params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      realname: name.value,
    }
    result = await R_rechargeInfoService(params)
  } else {
    let params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    }
    result = await rechargeInfoService(params)
  }
  rechargeRecords.value = result.data.items
  total.value = result.data.total
}
rechargeRecordsList();

// 充值对话框
const rechargeInformationVisible = ref(false)
const newRechargeRecord = ref(false)
const formLabelWidth = '80px'
const newRechargeRecordData = ref({
  paymentmethod: '',
  amount:''
});

function validateAmount(rule, value, callback) {
  if (isNaN(value)) {
    callback(new Error('充值金额必须为数字'));
  } else {
    callback();
  }
}

const rules={
  amount:[
    {required:true,message:'请填写充值金额',trigger:'blur'},
    { validator: validateAmount, trigger: 'blur' }
  ],
  paymentmethod:[
    {required:true,message:'请选择充值方式',trigger:'blur'}
  ]
}


const recharge=async()=>{
  let result = await rechargeNewRecordService(newRechargeRecordData.value)
  ElMessage.success("成功生成订单")
  rechargeRecordsList();
  userInfoStore.userInfo.accountbalance += Number(newRechargeRecordData.value.amount);
  rechargeInformationVisible.value = false;
}


import {rechargeRecordDownloadService,cancelPayService} from "@/api/recharge.js"
const downloadRechargeRecord=async (index,row)=>{
  const recordid=row.recordid;
  let result = await rechargeRecordDownloadService(recordid)
  // 假设result.data是包含下载链接的网址
  const downloadUrl = result.data;
  // 创建一个新的<a>标签，用于下载文件
  const link = document.createElement('a');
  link.href = downloadUrl;
  // 可以设置下载的文件名
  link.download = row.recordid+'recharge_record.pdf'; // 根据需要修改文件名
  // 模拟点击<a>标签来下载文件
  document.body.appendChild(link);
  link.click();
  // 下载完成后移除<a>标签
  document.body.removeChild(link);
}


const message = ref('');
const load = () => {
  // 这里是加载数据的函数实现
};


const dialogVisible=ref(false)
const res=ref()
const pay = async (index,row) => {
  if (window.confirm('确认支付？是否继续?')) {
    window.open('http://z9cf88.natappfree.cc/alipay/pay?recordid='+row.recordid)
    message.value = '付款成功';
    load();
  } else {
    message.value = '已取消付款';
    load();
  }
};

//取消支付
const cancel = async (index,row) => {
  await cancelPayService(row.recordid)
  ElMessage.success("取消支付成功")
  rechargeRecordsList();
}
</script>


<template>
  <el-container class="container">
    <!-- 余额显示区域 -->
    <el-header>
      <el-row>
        <el-col :span="3" v-if="userInfoStore.userInfo.usertype===0">
          <p><strong>余额：{{ userInfoStore.userInfo.accountbalance }}</strong></p>
          <!-- 添加充值按钮 -->
        </el-col>
        <el-col :span="2" v-if="userInfoStore.userInfo.usertype===0">
          <el-button type="danger"  @click="rechargeInformationVisible=true;">充值</el-button>
        </el-col>
        <el-col :span="12">
          <el-form inline v-if="isAdmin">
            <el-form-item>
              <el-input v-model="name" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="rechargeRecordsList">查询</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-header>
    <!-- 表格区域 -->
    <el-main>
      <el-table :data="rechargeRecords" style="width: 100%" :row-style="{height: '50px'}" stripe>
        <el-table-column prop="rechargetime" label="日期" ></el-table-column>
        <el-table-column prop="amount" label="充值金额" ></el-table-column>
        <el-table-column prop="balanceafter" label="充值后余额" > </el-table-column>
        <el-table-column prop="paymentmethod" label="支付方式" ></el-table-column>
        <el-table-column prop="paystatus" label="支付状态">
          <template #default="scope">
            <span v-if="scope.row.paystatus === 0">待支付</span>
            <span v-else-if="scope.row.paystatus === 1">已支付</span>
            <span v-else-if="scope.row.paystatus === 2">取消支付</span>
          </template>
        </el-table-column>
        <el-table-column prop="realname" label="用户名" v-if="isAdmin" ></el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template #default="scope">
            <el-button size="small" v-if="scope.row.paystatus===0" type="primary" @click="pay(scope.$index, scope.row)">
              去支付
            </el-button>
            <el-button size="small" v-if="scope.row.paystatus===0" type="danger" @click="cancel(scope.$index, scope.row)">
              取消支付
            </el-button>
            <el-button size="small" type="primary" @click="downloadRechargeRecord(scope.$index, scope.row)" :disabled="scope.row.paystatus!==1">
              下载充值账单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[ 5 , 8 ,10, 15]"
                     layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
                     @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
    </el-main>
  </el-container>
  <el-dialog v-model="rechargeInformationVisible" title="填写支付信息" width="500">
    <el-form :model="newRechargeRecordData" :rules="rules">
      <el-form-item prop="amount" label="充值金额" :label-width="formLabelWidth">
        <el-input v-model="newRechargeRecordData.amount" placeholder="请填写支付金额" />
      </el-form-item>
      <el-form-item prop="paymentmethod" label="支付方式" :label-width="formLabelWidth">
        <el-select v-model="newRechargeRecordData.paymentmethod" placeholder="请选择支付方式">
          <el-option label="微信支付" value="微信支付" disabled/>
          <el-option label="支付宝支付" value="支付宝支付" />
        </el-select>
      </el-form-item>
    </el-form>
    <el-dialog v-model="dialogVisible">
      {{res.value}}
    </el-dialog>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="rechargeInformationVisible = false">取消支付</el-button>
        <el-button type="primary" @click="recharge">
          生成支付订单
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>



<style scoped>

.container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.balance {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
}
.balance-info {
  flex: 1; /* 使余额信息占据剩余空间 */
  display: flex;
  align-items: center; /* 垂直居中对齐余额文本和按钮 */
}
/* 根据需要添加更多样式 */
</style>